function [m, ncases, ndim] = param2mat(p)
% Converts a variable with vectorized parameters into a matrix

if nargin == 0
    % Test case if no input
    p.a = [1 2 3];
    p.b = 4;[4 5 6];
    p.c = 5;[8 9];
    p.d = 6;[10 11];
    p.e = 7;
    p.f = true;
end

% Initialize
m = [];
TempStructure = [];
NameOfFields = fieldnames(p);
TempStructureLengths = [];

% Determine Scalars and Vectors
kk= 1;
for ii = 1:length(NameOfFields);
    TempField = getfield(p,NameOfFields{ii});
    if numel(TempField) == 1
        m = setfield(m,NameOfFields{ii},TempField);
    else
        [dim1 dim2] = size(TempField);
        if dim2 > dim1
            TempField = TempField';
        end
        TempStructure = setfield(TempStructure,NameOfFields{ii},TempField);
        TempStructureLengths(kk) = length(TempField);
        kk = kk+1;
    end
end

if kk > 2
    %Create big matrix
    NameOfVectorFields = fieldnames(TempStructure);
    for ii = 1: length(NameOfVectorFields)
        ReplicationVector = TempStructureLengths;
        ReplicationVector(ii) = 1;
        vector = getfield(TempStructure,NameOfVectorFields{ii});
        PermuteVector = permute(vector,[fliplr(1:ii) (ii+1:length(NameOfVectorFields))]);
        NewMatrix = repmat(PermuteVector,ReplicationVector);
        m = setfield(m,NameOfVectorFields{ii},NewMatrix);
    end
    % Get Number of Cases
    ncases = numel(NewMatrix);
    ndim = ndims(NewMatrix);
elseif kk == 1
    % Only one case
    ncases = 1;
else 
    % Only 1 vector
    NameOfVectorFields = fieldnames(TempStructure);
    vector = getfield(TempStructure,NameOfVectorFields{1});
    m = setfield(m,NameOfVectorFields{1},vector);
    ncases = length(vector);
end
end